package operation

import (
	"../common"
	"../web"
	"encoding/json"
	"strings"
)

type OperCustomerObj struct {
	common.BaseHandler
}

func (self *OperCustomerObj) ParameterCheck() bool {
	s_ssns := strings.TrimSpace(self.Ctx.Params["ssn"])
	s_cust := strings.TrimSpace(self.Ctx.Params["custid"])
	s_wono := self.Ctx.Params["wono"]
	s_stat := self.Ctx.Params["station"]
	s_line := self.Ctx.Params["line"]

	err := ""
	status := common.GetScanStatus(self.Ctx, s_stat)
	if !status {
		err = common.GetText(self.Lang, "System is busy, please wait a moment and try again.")
	}

	if s_ssns == "" {
		err = common.GetText(self.Lang, "Please input the Product No.")
	}
	if s_cust == "" {
		err = common.GetText(self.Lang, "Please input the Customer ID.")
	}
	if err != "" {
		iRtnData := *common.FetchOneRowPtr(
			`SELECT TOP 1 ISNULL(PASSED, 0) 
               FROM SFC_PASSED(NOLOCK) 
          	  WHERE WONO=? 
            	AND STATION=?`,
			self.Usr.Conn, new(common.RecDataStr), s_wono, s_stat)
		passedqty := iRtnData.(common.RecDataStr).Data
		dict_js, _ := json.Marshal(map[string]string{"result": err, "passedqty": passedqty, "printstr": "", "urltype": ""})
		self.Ctx.ResponseWriter.Write(dict_js)
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_ssns)
	self.Sqlparas = append(self.Sqlparas, s_cust)
	self.Sqlparas = append(self.Sqlparas, s_wono)
	self.Sqlparas = append(self.Sqlparas, s_stat)
	self.Sqlparas = append(self.Sqlparas, s_line)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)

	return true
}

func (self *OperCustomerObj) SqlQueryExecute() {
	s_wono := self.Sqlparas[1].(string)
	s_stat := self.Sqlparas[2].(string)
	common.SetScanStatus(self.Ctx, s_stat, false)
	spRtnData := *common.FetchOneRowPtr(
		`sp_SSNScanCustomer ?, ?, ?, ?, ?, ?`,
		self.Usr.Conn, new(common.SPReturn), self.Sqlparas...)
	common.SetScanStatus(self.Ctx, s_stat, true)
	err := common.GetTextSP(self.Lang, spRtnData)

	iRtnData := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(PASSED, 0) 
           FROM SFC_PASSED(NOLOCK) 
          WHERE WONO=? 
            AND STATION=?`,
		self.Usr.Conn, new(common.RecDataStr), s_wono, s_stat)
	passedqty := iRtnData.(common.RecDataStr).Data

	dict_js, _ := json.Marshal(map[string]string{"result": err, "passedqty": passedqty})
	self.Ctx.ResponseWriter.Write(dict_js)
}

func CustomerScanHandler(ctx *web.Context) {
	self := new(OperCustomerObj)
	self.Ctx = ctx
	self.DoJson(self)
}
